
package com.xtsoft.platform.task.service.impl;

import com.xtsoft.core.common.YesNo;
import com.xtsoft.platform.base.system.domain.SysOrganize;
import com.xtsoft.platform.base.system.domain.SysUser;

import com.xtsoft.platform.base.system.repository.SysUserRepository;
import com.xtsoft.platform.globe.Constants.Constants;
import com.xtsoft.platform.globe.enums.InfTaskState;
import com.xtsoft.platform.globe.enums.TaskBugType;
import com.xtsoft.platform.task.domain.InfTask;
import com.xtsoft.platform.task.domain.TaskBug;
import com.xtsoft.platform.task.domain.TaskCalend;
import com.xtsoft.platform.task.repository.InfTaskRepository;
import com.xtsoft.platform.task.repository.TaskCommentRepository;
import com.xtsoft.platform.task.service.InfTaskService;
import jakarta.servlet.http.HttpServletRequest;
/*
*    上海信拓信息技术有限公司 Koala企业综合信息管理系统
*    Copyright (C) 2010-2015 ShangHai XinTuo Software Inc.
*/
import org.springframework.beans.factory.annotation.Autowired;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


import jakarta.transaction.Transactional;

import org.springframework.stereotype.Service;

import com.xtsoft.core.repository.QueryFilter;
import com.xtsoft.core.repository.QueryResult;
import com.xtsoft.core.service.impl.GenericServiceImpl;
import com.xtsoft.core.utils.BeanUtil;
import com.xtsoft.core.utils.NodeUtils;
import com.xtsoft.core.utils.ResultMsg;
import com.xtsoft.core.utils.StringUtils;
import com.xtsoft.core.utils.tree.CommonTreeNode;
import com.xtsoft.core.utils.tree.TreeBuilder;

@Service("infTaskService")
public class InfTaskServiceImpl extends GenericServiceImpl<InfTask, String, InfTaskRepository>
		implements InfTaskService {

	@Autowired
	public InfTaskRepository infTaskRepository;

	@Autowired
	public SysUserRepository sysUserRepository;

	@Autowired
	public TaskCommentRepository taskCommentRepository;

	@Override
	public SysOrganize sysOrganize() {
		return infTaskRepository.sysOrganize();
	}

	/**
	 * 构建所有任务树
	 * 
	 * @throws IntrospectionException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws SecurityException
	 * @throws NoSuchFieldException
	 */




	@Override
	public List<CommonTreeNode> getAllInfTaskTree() throws NoSuchFieldException, SecurityException,
			IllegalArgumentException, IllegalAccessException, InvocationTargetException, IntrospectionException {

		List<InfTask> list = infTaskRepository.getByIsProject(YesNo.Yes.getIntValue());
		InfTask infTask = new InfTask();
		infTask.setNodeId(Constants.RootNode);
		infTask.setInfTaskId(Constants.RootNode);
		infTask.setTaskName("项目列表");
		infTask.setRecordSort(1);
		list.add(infTask);

		// 构建树节点，当提供了排序属性
		TreeBuilder<InfTask> treeBuilder = new TreeBuilder();
		List<CommonTreeNode> menuList = treeBuilder.build(list, "infTaskId", "nodeId", "parentNodeId", "taskName", null,
				"recordSort", null);

		return menuList;

	}

	/**
	 * 构建所有任务树
	 * 
	 * @throws IntrospectionException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws SecurityException
	 * @throws NoSuchFieldException
	 */
	@Override
	public List<CommonTreeNode> getAllTree(boolean needRootNode, SysUser user) throws NoSuchFieldException, SecurityException,
			IllegalArgumentException, IllegalAccessException, InvocationTargetException, IntrospectionException {
		// TODO Auto-generated method stub
		//过滤 根据登录用户所在的企业显示该企业下的项目
		//判断如果当前用户是超级管理员则查看所有
		List<InfTask> list = null;
		if(sysUserRepository.checkAdmin(user.getUserId(),Constants.AdminRole)>YesNo.No.getIntValue()) {
			list = infTaskRepository.findAll();
		}else {
		   list = infTaskRepository.findByOrganizeId(user.getSysOrganize().getOrganizeId());
		}
		
		InfTask rootNode = null;
		if (needRootNode) {
			rootNode = new InfTask();
			// 主键
			rootNode.setInfTaskId(Constants.RootNode);
			// 节点id
			rootNode.setNodeId(Constants.RootNode);
			rootNode.setTaskName("项目列表");
			rootNode.setIsProject(YesNo.Yes.getIntValue());
			rootNode.setRecordSort(1);
			list.add(rootNode);
		}
		for (InfTask infTask : list) {
			if(infTask.getIsProject()==0) {
				infTask.setIcon("");
			}else {
				infTask.setIcon("x-fa fa-save");
			}
		}
		TreeBuilder<InfTask> treeBuilder = new TreeBuilder();
		List<CommonTreeNode> result = treeBuilder.build(list, "infTaskId", "nodeId", "parentNodeId", "taskName", "icon",
				"recordSort", "isProject");
		return result;

		// 构建树节点,当提供了排序属性，则构建排序树
		/**
		 * CommonTree<InfTask, String, String> treeBuilder = new CommonTreeImpl<InfTask,
		 * String, String>(list, "infTaskId", "nodeId", "parentNodeId","recordSort");
		 * List result = new ArrayList(); if(needRootNode) { result =
		 * treeBuilder.buildTree(rootNode); }else { result = treeBuilder.buildTree(); }
		 * 
		 * return result;
		 */
	}

	/**
	 * 根据父ID获取下面的子节点
	 * 
	 * @throws IntrospectionException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws SecurityException
	 * @throws NoSuchFieldException
	 */
	@Override
	public List<InfTask> findByParentNodeId(String parentNodeId) {
		// TODO Auto-generated method stub
		return infTaskRepository.findByParentNodeId(parentNodeId);
	}

	/**
	 * 
	 * <p>
	 * 根据节点查询任务或者项目
	 * </p>
	 * 
	 * @param nodeId
	 * @return
	 * @return List<InfTask>
	 * @throws @author litao
	 * @date 2020年8月27日
	 * @time 上午9:59:53
	 */
	@Override
	public List<InfTask> findByNodeId(String nodeId) {
		// TODO Auto-generated method stub
		return infTaskRepository.findByNodeId(nodeId);
	}

	/**
	 * 
	 * <p>
	 * 修改infTask的编辑时间，编辑人，以及状态
	 * </p>
	 * 
	 * @param infTask
	 * @return void
	 * @throws @author litao
	 * @date 2020年8月31日
	 * @time 上午10:13:13
	 */
	@Override
	public void updateStateAndDate(InfTask infTask, SysUser sysUser) {
		// TODO Auto-generated method stub
		infTask.setUpdateTime(new Date().getTime());
		infTask.setUpdateUserId(sysUser.getUserId());
	}

	@Override
	public Map<String, Object> getInfTaskCount(String userId) {
		// TODO Auto-generated method stub
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Calendar cal = Calendar.getInstance();
		SysUser user = sysUserRepository.getOne(userId);
		// 当前月份
		int months = cal.get(Calendar.MONTH) + 1;
		String month = months + "";
		if (months <= 9) {
			month = "0" + month;
		}
		// 当前年份
		int year = cal.get(Calendar.YEAR);
		// 当前日份
		int days = cal.get(Calendar.DATE);
		String day = days + "";
		if (days <= 9) {
			day = "0" + days;
		}
		String planDate = year + "-" + month;
		// 获取本月任务
		int monthCount = 0;
		// 获取今日任务
		int dayCount = 0;
		//获取本月未完成任务
		int monthNoCount = 0;
		//获取本月完成任务
		int monthSuccesCount = 0;
		if(sysUserRepository.checkAdmin(userId, Constants.AdminRole) != 0) {
			//如果是超级管理员则查看所有本月任务
			monthCount = infTaskRepository.findInfTaskCountByPlanDate(planDate);
			//所有今日任务
			planDate = year + "-" + month + "-" + day;
			dayCount = infTaskRepository.findInfTaskCountDayByPlanDate(planDate);
			//所有本月未完成任务
			planDate = year + "-" + month;
			monthNoCount = infTaskRepository.findInfTaskNoCountByPlanDate(planDate);
			//获取所有本月完成任务
			monthSuccesCount = infTaskRepository.findInfTaskSuccesCountByPlanDate(planDate);
		}else if(sysUserRepository.checkAdmin(userId, Constants.SystemRole) != 0) {
			//如果是公司系统管理员 则统计这个企业的
			String organizeId = user.getSysOrganize().getOrganizeId();
			monthCount = infTaskRepository.findInfTaskCountByOrganizeIdAndPlanDate(organizeId,planDate);
			//所有今日任务
			planDate = year + "-" + month + "-" + day;
			dayCount = infTaskRepository.findInfTaskCountDayByOrganizeIdAndPlanDate(organizeId, planDate);
			//所有本月未完成任务
			planDate = year + "-" + month;
			monthNoCount = infTaskRepository.findInfTaskNoCountByOrganizeIdAndPlanDate(organizeId, planDate);
			//获取所有本月完成任务
			monthSuccesCount = infTaskRepository.findInfTaskSuccesCountByOrganizeIdAndPlanDate(organizeId, planDate);
		}else {
			//如果都不是则是个人用户 查询个人的
			monthCount = infTaskRepository.findInfTaskCountByPlanDate(userId, planDate);
			planDate = year + "-" + month + "-" + day;
			dayCount = infTaskRepository.findInfTaskCountDayByPlanDate(userId, planDate);
			//所有本月未完成任务
			planDate = year + "-" + month;
			monthNoCount = infTaskRepository.findInfTaskNoCountByPlanDate(userId, planDate);
			//获取本月完成的任务
			monthSuccesCount = infTaskRepository.findInfTaskSuccesCountByPlanDate(userId, planDate);
		}
		// 今日任务
		resultMap.put("dayTask", dayCount);
		// 本月任务
		resultMap.put("monthTask", monthCount);
		// 本月未完成任务
		resultMap.put("monthNoCount", monthNoCount);
		// 本月完成任务
		resultMap.put("monthSuccesCount", monthSuccesCount);
		return resultMap;
	}

	@Override
	public List<InfTask> findInfTaskDayByPlanDate(String userId) {
		// TODO Auto-generated method stub
		Calendar cal = Calendar.getInstance();
		// 当前月份
		int months = cal.get(Calendar.MONTH) + 1;
		String month = months + "";
		if (months <= 9) {
			month = "0" + month;
		}
		// 当前年份
		int year = cal.get(Calendar.YEAR);
		// 当前日份
		int days = cal.get(Calendar.DATE);
		String day = days + "";
		if (days <= 9) {
			day = "0" + days;
		}
		String planDate = year + "-" + month + "-" + day;
		List<InfTask> lisTasks = infTaskRepository.findInfTaskDayByPlanDate(userId, planDate);
		return lisTasks;
	}

	@Override
	public List<InfTask> findInfTaskMonthByPlanDate(String userId) {
		// TODO Auto-generated method stub
		Calendar cal = Calendar.getInstance();
		// 当前月份
		int months = cal.get(Calendar.MONTH) + 1;
		String month = months + "";
		if (months <= 9) {
			month = "0" + month;
		}
		// 当前年份
		int year = cal.get(Calendar.YEAR);
		// 当前日份
		int days = cal.get(Calendar.DATE);
		String day = days + "";
		if (days <= 9) {
			day = "0" + days;
		}
		String planDate = year + "-" + month;
		// 获取当前用户本月任务
		List<InfTask> monthList = infTaskRepository.findInfTaskMonthByPlanDate(userId, planDate);
		return monthList;
	}

	@Transactional
	@Override
	public ResultMsg addTask(InfTask infTask, SysUser user) {
		ResultMsg resultMsg = new ResultMsg();
		if (StringUtils.isEmpty(infTask.getParentNodeId())) {
			infTask.setParentNodeId(Constants.RootNode);
		}
		if(infTask.getRecordSort()==null||infTask.getRecordSort()==0) {
			infTask.setRecordSort(findMaxRecordSortByParentNodeId(infTask.getParentNodeId())+YesNo.Yes.getIntValue());
		}
		// 设置延期
		infTask.setIsDelayed(YesNo.No.getIntValue());
		// 设置项目状态，如果当前时间等于或者小于任务开始时间则状态为开始
		if (new Date().getTime() >= infTask.getPlanStartDate().getTime()) {
			infTask.setState(YesNo.Yes.getIntValue());
		} else if (new Date().getTime() <= infTask.getPlanStartDate().getTime()) {
			infTask.setState(YesNo.No.getIntValue());
		}

		// 生成nodeId
		String nodeId = "";
		if (infTask.getParentNodeId().equals(Constants.RootNode)) {
			nodeId = NodeUtils.createNodeIdWithParent(infTaskRepository.findMaxNodeId(infTask.getParentNodeId()),
					infTask.getParentNodeId(), Constants.CodeLength, true, true);
		} else {
			nodeId = NodeUtils.createNodeIdWithParent(infTaskRepository.findMaxNodeId(infTask.getParentNodeId()),
					infTask.getParentNodeId(), Constants.CodeLength, true, false);
		}
		infTask.setNodeId(nodeId);

		// 其他设置项
		infTask.setUsername(user.getLoginId());
		infTask.setUpdateUserId(user.getUserId());
		infTask.setUpdateTime(new Date().getTime());
		infTask.setOrganizeId(user.getSysOrganize().getOrganizeId());

		resultMsg.setData(infTaskRepository.save(infTask));
		resultMsg.setSuccess(true);
		return resultMsg;
	}

	@Override
	public List<InfTask> userConvert(List<InfTask> list) {
		// TODO Auto-generated method stub
		List<InfTask> result = new ArrayList<InfTask>();
		List<SysUser> users = sysUserRepository.findAll();
		result = list.stream()
				.map(infTask -> users.stream()
				.filter(user -> user.getUserId().equals(infTask.getUserId()))
				.findFirst().map(user ->{
					infTask.setUserId(user.getUsername());
					return infTask;
				}).orElse(null))
				.collect(Collectors.toList());
		//计算任务缺陷
		for (InfTask infTask : result) {
			
			//任务缺陷
			List<TaskBug> taskBugList = infTask.getTaskBugs();
			int solve = 0;
			if(taskBugList.isEmpty()) {
				infTask.setTaskBug("0/0");
			}else {
				for (TaskBug taskBug : taskBugList) {
					if(taskBug.getState()== TaskBugType.Determined) {
						solve = solve+1;
					}
				}
				infTask.setTaskBug(solve+"/"+taskBugList.size());
			}
			//任务点评
			if(infTask.getTaskComment().isEmpty()) {
				infTask.setTaskCommitSize("");
			}else {
				infTask.setTaskCommitSize(infTask.getTaskComment().get(0).getTaskCommentId());
			}
			
		}
		
		/*
		 * for (InfTask infTask : list) {
		 * infTask.setUserId(sysUserRepository.getOne(infTask.getUserId()).getLoginId())
		 * ; infTaskList.add(infTask); }
		 */
		return result;
	}

//	@Override
//	public List<InfTask> getAllInfTaskByTaskComment(HttpServletRequest request) {
//		// TODO Auto-generated method stub
//		// 全部项目或者未评分项目
//		String infTaskId = request.getParameter("Q_infTaskId_S_EQ");
//		String parentNodeId = request.getParameter("Q_infTask_S_EQ");
//		Integer pages = 0;
//		Integer size = 0;
//		boolean isPage = true;
//
//		if (isPage) {
//			size = Integer.parseInt(request.getParameter("limit"));
//			pages = (Integer.parseInt(request.getParameter("page")) - 1) * size;
//		} else {
//			size = 100000;
//		}
//		List<InfTask> infTasks = infTaskRepository.getAllInfTaskByTaskCommentAndParentNodeId(parentNodeId, pages, size);
//		// 如果是否全部任务不为空
//		if (!StringUtils.isBlank(infTaskId)) {
//			// 如果是未评分项目
//			if (infTaskId.equals("1")) {
//				infTasks = infTaskRepository.getAllInfTaskByTaskCommentAndParentNodeId(parentNodeId, pages, size);
//			} else {
//				infTasks = infTaskRepository.findAll();
//			}
//		}
//		return infTasks;
//	}

	@Override
	public List<InfTask> getInfTaskByComment(String taskId) {
		// TODO Auto-generated method stub
		return infTaskRepository.getInfTaskByComment(taskId);
	}

	@Override
	public List<InfTask> findInfTaskByisProject(int isProject) {
		// TODO Auto-generated method stub
		return infTaskRepository.findByIsProject(isProject);
	}

	@Override
	public Map<String, List<TaskCalend>> findTaskByUserId(String userId) {
		// TODO Auto-generated method stub
		// 已经终止的任务
		List<InfTask> infTasks = infTaskRepository.findTaskByUserIdAndStateTwo(userId);
		// 未完成 但是时间已过的任务
		List<InfTask> infTasks2 = infTaskRepository.findTaskByUserIdAndStateThree(userId);
		// 未完成 但是时间未过的任务
		List<InfTask> infTasks3 = infTaskRepository.findTaskByUserIdAndStateOneOrZero(userId);
		// 未开始的任务
		List<InfTask> infTasks4 = infTaskRepository.findTaskByUserIdAndStateOneOrZeroAndPlanEndDate(userId);
		Map<String, List<TaskCalend>> resultMap = new HashMap<String, List<TaskCalend>>();
		// 已经完成
		List<TaskCalend> taskCalends = new ArrayList<TaskCalend>();
		for (InfTask infTask : infTasks) {
			TaskCalend taskCalend = new TaskCalend();
			taskCalend.setId(infTask.hashCode());
			taskCalend.setStartDate(infTask.getPlanStartDate());
			taskCalend.setEndDate(infTask.getPlanEndDate());
			taskCalend.setTitle(infTask.getSummary());
			taskCalend.setDescription(infTask.getTaskName());
			taskCalend.setDuration(infTask.getParentNodeId());
			taskCalends.add(taskCalend);
		}
		// 已经终止的任务
		List<TaskCalend> taskCalends2 = new ArrayList<TaskCalend>();
		for (InfTask infTask : infTasks2) {
			TaskCalend taskCalend = new TaskCalend();
			taskCalend.setId(infTask.hashCode());
			taskCalend.setStartDate(infTask.getPlanStartDate());
			taskCalend.setEndDate(infTask.getPlanEndDate());
			taskCalend.setTitle(infTask.getSummary());
			taskCalend.setDescription(infTask.getTaskName());
			taskCalend.setDuration(infTask.getParentNodeId());
			taskCalends2.add(taskCalend);
		}
		// 未完成
		List<TaskCalend> taskCalends3 = new ArrayList<TaskCalend>();
		for (InfTask infTask : infTasks3) {
			TaskCalend taskCalend = new TaskCalend();
			taskCalend.setId(infTask.hashCode());
			taskCalend.setStartDate(infTask.getPlanStartDate());
			taskCalend.setEndDate(infTask.getPlanEndDate());
			taskCalend.setTitle(infTask.getSummary());
			taskCalend.setDescription(infTask.getTaskName());
			taskCalend.setDuration(infTask.getParentNodeId());
			taskCalends3.add(taskCalend);
		}
		// 即将开始
		List<TaskCalend> taskCalends4 = new ArrayList<TaskCalend>();
		for (InfTask infTask : infTasks4) {
			TaskCalend taskCalend = new TaskCalend();
			taskCalend.setId(infTask.hashCode());
			taskCalend.setStartDate(infTask.getPlanStartDate());
			taskCalend.setEndDate(infTask.getPlanEndDate());
			taskCalend.setTitle(infTask.getSummary());
			taskCalend.setDescription(infTask.getTaskName());
			taskCalend.setDuration(infTask.getParentNodeId());
			taskCalends4.add(taskCalend);
		}
		resultMap.put("taskCalendList1", taskCalends);
		resultMap.put("taskCalendList2", taskCalends2);
		resultMap.put("taskCalendList3", taskCalends3);
		resultMap.put("taskCalendList4", taskCalends4);
		return resultMap;
	}

	@Override
	public String TaskTree(HttpServletRequest request, boolean isRight, String userIds) {
		// TODO Auto-generated method stub
		// 任务名称
		String taskName = request.getParameter("Q_taskName_S_LK");
		// 责任人
		String userId = request.getParameter("Q_userId_S_LK");
		// 状态
		String state = request.getParameter("Q_state_I_EQ");
		// 计划开始时间
		String planDate = request.getParameter("Q_planStartDate_D_GE");
		// 上级项目
		String parentNode = request.getParameter("Q_parentNodeId_S_LK");
		StringBuffer whereSql = new StringBuffer();
		// 如果任务名称不为空
		whereSql.append("1=1");
		if (!StringUtils.isBlank(taskName)) {
			whereSql.append("AND taskName like '%" + taskName + "%'");
		}
		if (!StringUtils.isBlank(userId)) {
			whereSql.append("AND userId='" + userId + "'");
		}
		if (!StringUtils.isBlank(state)) {
			whereSql.append("AND state=" + state);
		}
		if (!StringUtils.isBlank(planDate)) {
			whereSql.append("AND planStartDate='" + planDate + "'");
		}
		if (!StringUtils.isBlank(parentNode)) {
			whereSql.append("AND parentNodeId like '" + parentNode + "%'");
		}
		if (!isRight) {
			whereSql.append("AND userId='" + userIds + "'");
		}
		QueryResult<InfTask> resQueryResult = infTaskRepository.findAll(InfTask.class, 0, 15, whereSql.toString(), null,
				"recordSort DESC");
		String[] tree = new String[] { "nodeId", "parentNodeId", "taskName", "infTaskId", "planStartDate",
				"planEndDate", "realEndDate", "taskType", "updateTime", "summary" };
		List<InfTask> list = resQueryResult.getResultList();
		String result=null;
//		TreeBuilder2 treeBuilder = new TreeBuilder2();暂且把树注释掉
//		String result = treeBuilder.buildTree(list, tree, InfTask.class);
		return result;
	}

	@Transactional
	@Override
	public void perform(InfTask infTask) {
		// TODO Auto-generated method stub
		infTask.setState(InfTaskState.Finish.getValue());
		if (infTask.getPlanEndDate().getTime() > new Date().getTime()) {
			infTask.setIsDelayed(YesNo.No.getIntValue());
		} else {
			infTask.setIsDelayed(YesNo.Yes.getIntValue());
		}
		infTask.setRealEndDate(new Date());
		infTaskRepository.save(infTask);
	}

	public Map<String, List<TaskCalend>> findTaskByUserIdTwo() {
		Map<String, List<TaskCalend>> taskMap = new HashMap<String, List<TaskCalend>>();
		// 已经完成
		List<InfTask> infTasks = infTaskRepository.findTaskByUserIdAndStateTwoByAdmin();
		// 已终止
		List<InfTask> infTasks2 = infTaskRepository.findTaskByUserIdAndStateThreeByAdmin();
		// 未完成
		List<InfTask> infTasks3 = infTaskRepository.findTaskByUserIdAndStateOneOrZeroByAdmin();
		// 未开始
		List<InfTask> infTasks4 = infTaskRepository.findTaskByUserIdAndStateOneOrZeroAndPlanEndDateByAdmin();
		// 已经完成
		List<TaskCalend> taskCalends = new ArrayList<TaskCalend>();
		for (InfTask infTask : infTasks) {
			TaskCalend taskCalend = new TaskCalend();
			taskCalend.setId(infTask.hashCode());
			taskCalend.setStartDate(infTask.getPlanStartDate());
			taskCalend.setEndDate(infTask.getPlanEndDate());
			taskCalend.setTitle(infTask.getSummary());
			taskCalend.setDescription(infTask.getTaskName());
			taskCalend.setDuration(infTask.getParentNodeId());
			taskCalends.add(taskCalend);
		}
		// 已经终止的任务
		List<TaskCalend> taskCalends2 = new ArrayList<TaskCalend>();
		for (InfTask infTask : infTasks2) {
			TaskCalend taskCalend = new TaskCalend();
			taskCalend.setId(infTask.hashCode());
			taskCalend.setStartDate(infTask.getPlanStartDate());
			taskCalend.setEndDate(infTask.getPlanEndDate());
			taskCalend.setTitle(infTask.getSummary());
			taskCalend.setDescription(infTask.getTaskName());
			taskCalend.setDuration(infTask.getParentNodeId());
			taskCalends2.add(taskCalend);
		}
		// 未完成
		List<TaskCalend> taskCalends3 = new ArrayList<TaskCalend>();
		for (InfTask infTask : infTasks3) {
			TaskCalend taskCalend = new TaskCalend();
			taskCalend.setId(infTask.hashCode());
			taskCalend.setStartDate(infTask.getPlanStartDate());
			taskCalend.setEndDate(infTask.getPlanEndDate());
			taskCalend.setTitle(infTask.getSummary());
			taskCalend.setDescription(infTask.getTaskName());
			taskCalend.setDuration(infTask.getParentNodeId());
			taskCalends3.add(taskCalend);
		}
		// 即将开始
		List<TaskCalend> taskCalends4 = new ArrayList<TaskCalend>();
		for (InfTask infTask : infTasks4) {
			TaskCalend taskCalend = new TaskCalend();
			taskCalend.setId(infTask.hashCode());
			taskCalend.setStartDate(infTask.getPlanStartDate());
			taskCalend.setEndDate(infTask.getPlanEndDate());
			taskCalend.setTitle(infTask.getSummary());
			taskCalend.setDescription(infTask.getTaskName());
			taskCalend.setDuration(infTask.getParentNodeId());
			taskCalends4.add(taskCalend);
		}
		taskMap.put("taskCalendList1", taskCalends);
		taskMap.put("taskCalendList2", taskCalends2);
		taskMap.put("taskCalendList3", taskCalends3);
		taskMap.put("taskCalendList4", taskCalends4);
		return taskMap;
	}

	@Transactional
	@Override
	public ResultMsg editTask(InfTask infTask, SysUser user) throws IllegalAccessException, InvocationTargetException {
		// TODO Auto-generated method stub
		InfTask infTaskNew = infTaskRepository.getOne(infTask.getInfTaskId());
		BeanUtil.copyNotNullProperties(infTaskNew, infTask);
		infTaskNew.setUpdateUserId(user.getUserId());
		infTaskNew.setUsername(user.getLoginId());
		infTaskNew.setUpdateTime(new Date().getTime());
		InfTask result = infTaskRepository.save(infTaskNew);
		return new ResultMsg(true, "编辑成功！", result);
	}

	@Override
	public List<CommonTreeNode> getAllTaskTree(boolean needRootNode) throws NoSuchFieldException, SecurityException,
			IllegalArgumentException, IllegalAccessException, InvocationTargetException, IntrospectionException {
		// TODO Auto-generated method stub
		List<InfTask> list = infTaskRepository.getByIsProject(YesNo.Yes.getIntValue());
		InfTask rootNode = null;
		if (needRootNode) {
			rootNode = new InfTask();
			// 主键
			rootNode.setInfTaskId(Constants.RootNode);
			// 节点id
			rootNode.setNodeId(Constants.RootNode);
			rootNode.setTaskName("项目列表");
			rootNode.setIsProject(YesNo.Yes.getIntValue());
			rootNode.setRecordSort(1);
			list.add(rootNode);
		}

		TreeBuilder<InfTask> treeBuilder = new TreeBuilder();
		List<CommonTreeNode> result = treeBuilder.build(list, "infTaskId", "nodeId", "parentNodeId", "taskName", null,
				"recordSort", "isProject");
		return result;
	}
	@Override
	public String findDescriptById(String Id) {
		// TODO Auto-generated method stub
		return infTaskRepository.findDescriptById(Id);
	}

	@Override
	public int findMaxRecordSortByParentNodeId(String parentNodeId) {
		// TODO Auto-generated method stub
		InfTask infTask = infTaskRepository.findTopByParentNodeIdOrderByRecordSortDesc(parentNodeId);
		if(null == infTask) {
			return 0;
		}
		return infTask.getRecordSort();
	}

	@Override
	public void getMonth(QueryFilter<InfTask> filter) {
		// TODO Auto-generated method stub
		Calendar cal = Calendar.getInstance();
		// 当前月份
		int months = cal.get(Calendar.MONTH) + 1;
		String month = months + "";
		if (months <= 9) {
			month = "0" + month;
		}
		// 当前年份
		int year = cal.get(Calendar.YEAR);
		String planDate = year + "-" + month+"-"+"01";
		filter.addFilter("Q_planStartDate_D_GE", planDate);
	}

	@Override
	public void getDay(QueryFilter<InfTask> filter) {
		// TODO Auto-generated method stub
		Calendar cal = Calendar.getInstance();
		// 当前月份
		int months = cal.get(Calendar.MONTH) + 1;
		String month = months + "";
		if (months <= 9) {
			month = "0" + month;
		}
		// 当前年份
		int year = cal.get(Calendar.YEAR);
		// 当前日份
		int days = cal.get(Calendar.DATE);
		String day = days + "";
		if (days <= 9) {
			day = "0" + days;
		}
		String planDate = year + "-" + month + "-" + day;
		filter.addFilter("Q_planStartDate_D_EQ", planDate);
	}

	@Override
	public void getIncomplete(QueryFilter<InfTask> filter) {
		// TODO Auto-generated method stub
		Calendar cal = Calendar.getInstance();
		// 当前月份
		int months = cal.get(Calendar.MONTH) + 1;
		String month = months + "";
		if (months <= 9) {
			month = "0" + month;
		}
		// 当前年份
		int year = cal.get(Calendar.YEAR);
		String planDate = year + "-" + month+"-"+"01";
		filter.addFilter("Q_planStartDate_D_GE", planDate);
		filter.addFilter("Q_state_I_IN", "0,1");
	}

	@Override
	public Map<String, List<Map<String, Object>>> getProjectCount() {
		// TODO Auto-generated method stub
		Map<String, List<Map<String, Object>>> result = new HashMap<>();
		Calendar date = Calendar.getInstance();
		List<Map<String, Object>> lineList = new ArrayList<>();
		int year = date.get(Calendar.YEAR);
		StringBuffer buff = new StringBuffer("SELECT");
		for (int i = 1; i <= 12; i++) {
			String day = i + "";
			if (i <= 9) {
				day = "0" + i;
			}
			if (i == 12) {
				buff.append(" sum(CASE DATE_FORMAT(planStartDate,'%Y-%m') WHEN '" + (year +"-"+ day) + "' THEN 1 ELSE 0 END) '" + (year +"-"+ day) + "'");
			} else {
				buff.append(" sum(CASE DATE_FORMAT(planStartDate,'%Y-%m') WHEN '" + (year +"-"+ day) + "' THEN 1 ELSE 0 END) '" + (year +"-"+ day) + "',");
			}
		}
		buff.append(" from inf_task where isProject = 0");
		List<Object[]> list = infTaskRepository.nativeQuery(buff.toString());
		for (int i = 0; i < 12; i++) {
			Map<String, Object> map = new HashMap<>();
			map.put("name", i +1+ "月份");
			map.put("value", list.get(0)[i]);
			lineList.add(map);
		}
//		//获取最近五年的任务数量
//		for (int i = year-5; i < year; i++) {
//			int count = infTaskRepository.countByPlanStartDate(String.valueOf(i));
//			Map<String, Object> map = new HashMap<String, Object>();
//			map.put("name", i+"年");
//			map.put("value", count);
//			lineList.add(map);
//		}
		String sql = "SELECT SUM(CASE state WHEN 0 THEN 1 ELSE 0 END) '草稿',"
				+ "SUM(CASE state WHEN 1 THEN 1 ELSE 0 END) '开始'," + "SUM(CASE state WHEN 2 THEN 1 ELSE 0 END) '完成',"
				+ "SUM(CASE state WHEN 3 THEN 1 ELSE 0 END) '终止' from inf_task where isProject = 0";
		List<Object[]> list2 = infTaskRepository.nativeQuery(sql);
		
		List<Map<String, Object>> pieList = new ArrayList<>();
		Object[] object = list2.get(0);
		Map<String, Object> map1 = new HashMap<>();
		map1.put("name", "草稿状态");
		map1.put("value", object[0]);
		pieList.add(map1);

		Map<String, Object> map2 = new HashMap<>();
		map2.put("name", "开始状态");
		map2.put("value", object[1]);
		pieList.add(map2);

		Map<String, Object> map3 = new HashMap<>();
		map3.put("name", "完成状态");
		map3.put("value", object[2]);
		pieList.add(map3);

		Map<String, Object> map4 = new HashMap<>();
		map4.put("name", "终止状态");
		map4.put("value", object[3]);
		pieList.add(map4);
		
		result.put("lineList", lineList);
		result.put("pieList", pieList);
		return result;
	}

	@Override
	public boolean isDuty(SysUser user, InfTask task) {
		// TODO Auto-generated method stub
		if(user.getUserId().equals(task.getUserId())) {
			return true;
		}
		if(user.contains(Constants.AdminRole)) {
			return true;
		}
		return false;
	}
}